package yxy.apple.util;

import java.math.BigInteger;

public class BigIntegerUtility {

	//Binary(2), Quaternary(4), Octonary(8), Hexadecimal(16), Duotricemary(32), Hemidemary(64);

	private static final char[] NotationTable = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
			'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
			'U', 'V', 'W', 'X', 'Y', 'Z', '+', '/' };

	//0-9,a-z,A-Z,
	public static final int MinRadix = 2;//二进制
	public static final int NumbersRadix = 10;//十进制
	public static final int CaseInsensitiveRadix = 36;//大小写不敏感0-9，a-z
	public static final int NumbersAndLettersRadix = 62;//大小写敏感0-9,a-z, A-Z
	public static final int MaxRadix = 64;//大小写敏感0-9,a-z, A-Z, 另外加入两个符号“+”和“/”

	public static BigInteger parse(String string, int radix) {
		if (string == null || string.trim().length() == 0 || radix < MinRadix || radix > MaxRadix) {
			throw new IllegalArgumentException();
		}
		if (radix <= CaseInsensitiveRadix) {
			string = string.toLowerCase();
		}
		BigInteger value = BigInteger.ZERO;
		int length = string.length();
		for (int i = 0; i < length; i++) {
			char c = string.charAt(length - 1 - i);
			int v = 0;
			if (c >= '0' && c <= '9') {
				v = c - '0';
			} else if (c >= 'a' && c <= 'z') {
				v = c - 'a' + 10;
			} else if (c >= 'A' && c <= 'Z') {
				v = c - 'A' + 36;
			} else if (c == '+') {
				v = 62;
			} else if (c == '/') {
				v = 63;
			} else {
				throw new NumberFormatException(string);
			}
			if (v >= radix) {
				throw new NumberFormatException(string);
			}
			BigInteger tmp = BigInteger.valueOf(radix).pow(i).multiply(BigInteger.valueOf(v));
			value = value.add(tmp);
		}
		return value;
	}

	/**
	 * 
	 * 
	 * @param value
	 *            不支持负数
	 * @param radix
	 * @return
	 */
	public static String toString(BigInteger value, int radix) {
		if (radix < MinRadix || radix > MaxRadix || value.signum() < 0) {
			throw new IllegalArgumentException();
		}
		StringBuffer buffer = new StringBuffer();
		BigInteger divisor = BigInteger.valueOf(radix);
		convert(value, divisor, buffer);
		return buffer.toString();
	}

	private static void convert(BigInteger dividend, BigInteger divisor, StringBuffer buffer) {
		BigInteger remainder = dividend.mod(divisor);
		BigInteger quotient = dividend.divide(divisor);
		{
			char c = NotationTable[remainder.intValue()];
			buffer.insert(0, c);
		}
		if (quotient.compareTo(divisor) >= 0) {
			convert(quotient, divisor, buffer);
		} else if (quotient.compareTo(BigInteger.ZERO) > 0) {
			char c = NotationTable[quotient.intValue()];
			buffer.insert(0, c);
		}
	}
}
